import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Button, Divider, Form, InputNumber, Modal, Select, Space } from 'antd';
import TRNotification from '@/utils/notification';
import moment from 'moment';
import { forecastDataSource, dataSourceSave, detailedQuery } from '../../services';
import { PageLoading, TRAlert, TRMessage } from '@/components';
import { HttpCode } from '@/utils/contacts';
import { mat, ones } from '@josh-brown/vector';
import { getKHead, getPoints } from './helper';

const ModalDetailComponent = ({ onClose, pageQuery = {} }) => {
  const [data, setData] = useState([]);

  const [loading, setLoading] = useState(false);

  const [changed, setChanged] = useState(false);

  const [optionObj, setOptionObj] = useState({
    longSourceArr: [],
    mediumSourceArr: [],
    shortSourceArr: [],
  });

  const [headValue, setHeadValue] = useState({
    longSourceId: null,
    mediumSourceId: null,
    shortSourceId: null,
  });

  const SELECT_ARR = [
    {
      name: '短期预测',
      options: optionObj.shortSourceArr,
      key: 'shortSourceId',
    },
    {
      name: '中期预测',
      options: optionObj.mediumSourceArr,
      key: 'mediumSourceId',
    },
    {
      name: '长期预测',
      options: optionObj.longSourceArr,
      key: 'longSourceId',
    },
  ];

  useEffect(() => {
    fetch();
  }, []);

  const getAllDate = (start, end) => {
    let time = start;
    const arr = [];
    while (time !== end) {
      arr.push(time);
      time = moment(time).add(1, 'day').format('YYYY-MM-DD');
    }
    arr.push(end);
    return arr;
  };

  const fetch = async () => {
    setLoading(true);
    const params = {
      endDate: pageQuery.en,
      startDate: pageQuery.st,
      settlementUnitList: [pageQuery.s],
    };
    const servers = [await detailedQuery(params), await forecastDataSource(params)];
    Promise.all(servers).then((res) => {
      if (res?.length === 2) {
        const [res1, res2] = res;
        if (res1.statusCode === HttpCode.SUCCESS) {
          const len = getAllDate(params.startDate, params.endDate);
          const datas = mat(Object.values(res1?.results?.[pageQuery.s]))
            .transpose()
            .apply(ones(len.length))
            .toArray();
          let data = datas.map((i) => {
            return i / (len.length ? len.length : 1);
          });
          data = data.map((i, index) => ({ key: getKHead(index + 1), value: i }));
          setData(data);
        } else {
          TRMessage.error(res1?.message || '系统异常');
        }
        if (res2.statusCode === HttpCode.SUCCESS) {
          const { results } = res2;
          if (results?.length === 1) {
            const data = results[0][pageQuery.s];
            setOptionObj({
              longSourceArr: data.longSourceId || [],
              mediumSourceArr: data.mediumSourceId || [],
              shortSourceArr: data.shortSourceId || [],
            });
          }
        } else {
          TRMessage.error(res1?.message || '系统异常');
        }
      }
    });
    setLoading(false);
  };

  const handleCancel = async () => {
    // 取消
    let obj = { index: 1 };
    if (data.length > 0 && changed) {
      obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
    }
    obj?.index === 1 && onClose();
  };

  const handelSave = () => {
    Modal.confirm({
      title: '确认保存修改数据?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const points = getPoints(data);
        const params = {
          startDate: pageQuery.st,
          endDate: pageQuery.en,
          settlementUnit: pageQuery.s,
          ...headValue,
          points,
        };
        const res = await dataSourceSave(params);
        if (res.statusCode === HttpCode.SUCCESS) {
          TRMessage.success('保存成功!');
          onClose();
        } else {
          TRMessage.error(res?.message || '系统异常');
        }
      },
    });
  };

  const changeValue = (v, k) => {
    setChanged(true);
    let arr = data.slice();
    arr = arr.map((i) => (i.key === k ? { ...i, value: v } : i));
    setData(arr);
  };

  const headChange = (v, key) => {
    const data = headValue;
    data[key] = v;
    setHeadValue(data);
  };

  const _content = () => {
    const width = 200;
    if (loading) return <PageLoading />;
    return (
      <>
        <Space size={16}>
          {SELECT_ARR.map((i) => (
            <Form.Item key={i.key} label={i.name}>
              <Select
                placeholder={'请选择短期预测'}
                style={{ width: width }}
                onChange={(v) => headChange(v, i.key)}
              >
                {i.options.map((i) => (
                  <Select.Option key={i.dataSourceId} value={i.dataSourceId}>
                    {i.dataSourceName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          ))}
        </Space>
        <Divider style={{ margin: '0 0 10px 0' }} />
        <div style={{ fontSize: 16 }}>K值(%)</div>
        <div className={styles.kContent}>
          {data.map((i, k) => (
            <div className={styles.kBox} key={'_k' + k}>
              <div className={styles.kHead}>{i.key}</div>
              <div className={styles.kInp}>
                <InputNumber
                  bordered={false}
                  className={styles.kInput}
                  onChange={(v) => changeValue(v, i.key)}
                  value={i.value}
                />
              </div>
            </div>
          ))}
        </div>
      </>
    );
  };

  return (
    <Modal
      wrapClassName={styles.modal}
      visible={true}
      onCancel={handleCancel}
      width={'987px'}
      maskClosable={false}
      title={`数据源管理 (${pageQuery?.f2}) ${moment(pageQuery?.st).format('YYYYMMDD')}-${moment(
        pageQuery?.en,
      ).format('YYYYMMDD')}`}
      centered
      footer={
        !loading && (
          <Space size={16}>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" onClick={handelSave}>
              保存
            </Button>
          </Space>
        )
      }
    >
      {_content()}
    </Modal>
  );
};

class ModalDetail {
  __key__ = '';
  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalDetailComponent
            {...props}
            onClose={() => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve();
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ModalDetail();
